<template>
  <el-dialog v-model="props.modelValue" @close="close" :title="title" @open="openHandel" width="80%" top="1vh">
    <div class="dialog">
      <el-steps :active="stepsIndex" align-center>
        <el-step title="基本信息"/>
        <el-step title="正文"/>
        <el-step title="节点信息"/>
        <el-step title="历史关联"/>
      </el-steps>

      <el-form :model="form" v-show="stepsIndex == 0" :rules="rules1" ref="formRef0">
        <el-row>
          <el-col :span="12">
            <el-form-item label="名称" prop="name" label-width="140">
              <el-input v-model="form.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地区" prop="region" label-width="140">
              <el-cascader
                  style="width: 100%"
                  :props="{checkStrictly: true}"
                  :options="gansuOptions"
                  v-model="selectedOptions"
                  placeholder="请选择地区"
                  clearable
                  @change="handleChange">
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="类型" prop="type" label-width="140">
              <el-select v-model="form.type" placeholder="请选择类型" clearable>
                <el-option v-for="item in types" :key="item.id" :label="item.name" :value="item.id">{{ item.name }}
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标签" prop="tags" label-width="140">
              <el-select v-model="form.tags" multiple placeholder="请选择标签" clearable>
                <el-option v-for="item in tags" :key="item.id" :label="item.name" :value="item.id">{{ item.name }}
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="封面图" prop="cover" label-width="140">
              <el-upload
                  class="avatar-uploader"
                  action="/api/common/upload"
                  :show-file-list="false"
                  :on-success="uploadSuccess"
              >
                <el-image v-if="form.cover" :src="'/api' + form.cover" class="avatar"/>
                <el-icon v-else size="48" color="#d9d9d9">
                  <Plus/>
                </el-icon>
                <el-icon v-if="form.cover" class="avatar-delete" @click.stop="form.cover = ''">
                  <Delete/>
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-form :model="form" :rules="rules2" ref="formRef1" v-show="stepsIndex == 1">
        <el-row>
          <el-col>
            <el-form-item label-width="140" label="正文" prop="content">
              <Toolbar
                  style="border-bottom: 1px solid #ccc"
                  :editor="editorRef"
                  :defaultConfig="toolbarConfig"
                  mode="default"
              />
              <Editor
                  style="height: 500px; overflow-y: auto; width: 100%;"
                  v-model="form.content"
                  :defaultConfig="editorConfig"
                  mode="default"
                  @onCreated="handleCreated"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-form :model="form" :rules="rules3" ref="formRef2" v-show="stepsIndex == 2">
        <el-form-item label="朝代" prop="period" label-width="140">
          <el-select v-model="form.period" placeholder="请选择朝代" clearable>
            <el-option v-for="item in periods" :label="item.label" :value="item.value">{{ item.label }}</el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="文化背景" prop="cultural_background" label-width="140">
          <el-input type="textarea" v-model="form.cultural_background" placeholder="请输入文化背景"/>
        </el-form-item>
        <el-form-item label="工艺流程" prop="craft_process" label-width="140">
          <el-input type="textarea" v-model="form.craft_process" placeholder="请输入工艺流程"/>
        </el-form-item>
        <el-form-item label="文化价值" prop="cultural_value" label-width="140">
          <el-input type="textarea" v-model="form.cultural_value" placeholder="请输入文化价值"/>
        </el-form-item>
      </el-form>

      <!-- 新增历史关联表单 -->
      <el-form :model="form" ref="formRef3" v-show="stepsIndex == 3">
        <h3>历史人物关联</h3>
        <div v-for="(figure, index) in form.related_figures" :key="`figure-${index}`"
             style="border: 1px dashed #eee; padding: 10px; margin-bottom: 10px;">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="`名称`" :prop="`related_figures.${index}.name`" label-width="140"
                            :rules="{required: true, message: '请输入人物名称', trigger: 'blur'}">
                <el-input v-model="figure.name" placeholder="请输入历史人物名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12" style="display: flex; align-items: center;">
              <el-button type="danger" @click="removeFigure(index)" icon="Delete" circle></el-button>
            </el-col>
          </el-row>
          <el-form-item :label="`描述`" :prop="`related_figures.${index}.description`" label-width="140">
            <el-input type="textarea" v-model="figure.description" placeholder="请输入人物描述(非必填)"/>
          </el-form-item>
        </div>
        <div style="margin-bottom: 20px;">
          <el-button type="primary" @click="addFigure" icon="Plus">添加历史人物</el-button>
        </div>

        <h3>历史事件关联</h3>
        <div v-for="(event, index) in form.related_events" :key="`event-${index}`"
             style="border: 1px dashed #eee; padding: 10px; margin-bottom: 10px;">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="`名称`" :prop="`related_events.${index}.name`" label-width="140"
                            :rules="{required: true, message: '请输入事件名称', trigger: 'blur'}">
                <el-input v-model="event.name" placeholder="请输入历史事件名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12" style="display: flex; align-items: center;">
              <el-button type="danger" @click="removeEvent(index)" icon="Delete" circle></el-button>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="`时间`" :prop="`related_events.${index}.date`" label-width="140">
                <el-input v-model="event.date" placeholder="请输入事件发生时间(非必填)"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item :label="`描述`" :prop="`related_events.${index}.description`" label-width="140">
            <el-input type="textarea" v-model="event.description" placeholder="请输入事件描述(非必填)"/>
          </el-form-item>
        </div>
        <div>
          <el-button type="primary" @click="addEvent" icon="Plus">添加历史事件</el-button>
        </div>
      </el-form>
    </div>

    <template #footer v-if="stepsIndex == 3">
      <el-button @click="emits('update:modelValue', false)">取消</el-button>
      <el-button @click="back" type="info">上一步</el-button>
      <el-button type="primary" @click="commit(formRef3)">确定</el-button>
    </template>
    <template #footer v-else>
      <el-button @click="emits('update:modelValue', false)">取消</el-button>
      <el-button @click="back" type="info" v-if="stepsIndex !== 0">上一步</el-button>
      <el-button type="primary" @click="next(stepsIndex === 0 ? formRef0 : stepsIndex === 1 ? formRef1 : formRef2)">
        下一步
      </el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import {defineProps, defineEmits, ref, computed, reactive, onBeforeUnmount, shallowRef, onMounted, nextTick} from 'vue'
import {typesApi} from '@/api/type.js'
import {detailByID, goodsAddAndUpdate} from '@/api/goods.js'
import {tagsApi} from '@/api/tag.js'
import {Plus} from "@element-plus/icons-vue"
import '@wangeditor/editor/dist/css/style.css' // 引入富文本编辑器样式
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import request from "@/utils/request.js"
import {ElMessage} from "element-plus"
import gansuOptions from '@/utils/gansu_region_data.js'
import splitLocation from "@/utils/splitLocation.js";


// 步骤索引，用于控制表单步骤的显示
const stepsIndex = ref(0)

// 定义组件事件
const emits = defineEmits(['update:modelValue', 'refresh'])

// 富文本编辑器实例
const editorRef = shallowRef()

// 编辑器自定义图片视频上传方法
const editUpload = async (file, insertFn) => {
  const formData = new FormData()
  formData.append('file', file)
  try {
    const res = await request('/common/upload', {
      method: 'post',
      data: formData
    })
    nextTick(() => {
      insertFn(`/api${res.data.filePath}`)
    })
  } catch (e) {
    console.log(e)
  }
}

// 编辑器工具栏配置
const toolbarConfig = {}

// 编辑器基础配置
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      // 禁用自动上传
      server: null,
      fieldName: null,
      // 使用自定义上传
      customUpload: editUpload
    },
    uploadVideo: {
      server: null,
      fieldName: null,
      customUpload: editUpload
    }
  }
}

// 表单引用
const formRef0 = ref(null)
const formRef1 = ref(null)
const formRef2 = ref(null)
const formRef3 = ref(null)

// 下一步方法，包含表单验证
const next = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      stepsIndex.value += 1;
    }
  })
}

// 返回上一步
const back = () => {
  stepsIndex.value -= 1;
}

// 计算属性：根据id判断是新增还是编辑
const title = computed(() => {
  return props.id === -1 ? '新增' : '编辑'
})

// 类型和标签数据
const types = ref([])
const tags = ref([])

// 表单数据对象
const form = ref({
  id: '',
  name: '',
  type: '',
  cover: '', //封面图
  tags: [], //标签
  content: '',
  period: '', //朝代
  region: '', //地区
  cultural_background: '', //文化背景
  craft_process: '', //工艺流程
  cultural_value: '', //文化价值
  related_figures: [], //关联历史人物
  related_events: [], //关联历史事件
})

// 表单验证规则
const rules1 = reactive({
  name: {required: true, message: '请输入名称', trigger: 'blur'},
  region: {required: true, message: '请输入地区', trigger: 'blur'},
  type: {required: true, message: '请选择类型', trigger: ['change', 'blur']},
  cover: {required: true, message: '请上传封面图', trigger: 'blur'},
})
const rules2 = reactive({
  content: {required: true, message: '请输入简介', trigger: 'blur'}
})
const rules3 = reactive({
  period: {required: true, message: '请输入朝代', trigger: 'blur'},
  cultural_background: {required: true, message: '请输入文化背景', trigger: 'blur'},
  craft_process: {required: true, message: '请输入工艺流程', trigger: 'blur'},
  cultural_value: {required: true, message: '请输入文化价值', trigger: 'blur'},
})

// 封面图上传成功回调
const uploadSuccess = (res) => {
  form.value.cover = res.data.filePath
}

// 组件属性定义
const props = defineProps({
  id: {
    type: Number,
    default: -1
  },
  modelValue: {
    type: Boolean,
    default: false
  }
})

// 获取分类数据
const getTypes = async () => {
  const res = await typesApi()
  types.value = res.data
}

// 获取标签数据
const getTags = async () => {
  const res = await tagsApi()
  tags.value = res.data
}

const selectedOptions = ref([])
const handleChange = value => {
  if (!value) {
    form.value.region = ''
    return;
  }
  let str;
  value.forEach((item) => {
    if (item) {
      str += item
    }
  })
  form.value.region = str.replace('undefined', '')
}

// dialog打开时的处理函数
const openHandel = async () => {
  await getTypes()
  await getTags()
  if (props.id === -1) {
    // 初始化空数组
    form.value.related_figures = [];
    form.value.related_events = [];
    return;
  }
  const res = await detailByID(props.id)
  form.value = res.data
  form.value.tags = res.data.tags.map(item => item.id)

  //处理历史信息
  form.value.period = res.data.history?.period
  form.value.region = res.data.history?.region
  form.value.cultural_background = res.data.history?.cultural_background
  form.value.craft_process = res.data.history?.craft_process
  form.value.cultural_value = res.data.history?.cultural_value

  //处理地区select绑定值
  selectedOptions.value = splitLocation(res.data.history?.region)

  // 处理知识图谱数据
  if (res.data.knowledgeGraph) {
    // 处理历史人物
    const historicalFigures = res.data.knowledgeGraph.historicalFigures || [];
    form.value.related_figures = historicalFigures.map(figure => ({
      name: figure.name || '',
      description: figure.description || ''
    }));

    // 处理历史事件
    const historicalEvents = res.data.knowledgeGraph.historicalEvents || [];
    form.value.related_events = historicalEvents.map(event => ({
      name: event.name || '',
      date: event.date || '',
      description: event.description || ''
    }));
  } else {
    // 确保有空数组
    form.value.related_figures = [];
    form.value.related_events = [];
  }
}

// 表单提交方法
const commit = async () => {
  const res = await goodsAddAndUpdate(form.value)
  if (res.code === 200) {
    ElMessage.success(res.message)
    emits('update:modelValue', false)
    emits('refresh')
  } else {
    ElMessage.error(res.message)
  }
}




const periods = reactive([
  {label: "现代", value: "现代"},
  {label: "民国", value: "民国"},
  {label: "清朝", value: "清朝"},
  {label: "明朝", value: "明朝"},
  {label: "元朝", value: "元朝"},
  {label: "南宋（辽、西夏、金）", value: "南宋（辽、西夏、金）"},
  {label: "北宋", value: "北宋"},
  {label: "五代十国", value: "五代十国"},
  {label: "唐朝", value: "唐朝"},
  {label: "隋朝", value: "隋朝"},
  {label: "南北朝", value: "南北朝"},
  {label: "东晋十六国", value: "东晋十六国"},
  {label: "西晋", value: "西晋"},
  {label: "三国（魏、蜀、吴）", value: "三国（魏、蜀、吴）"},
  {label: "东汉", value: "东汉"},
  {label: "西汉", value: "西汉"},
  {label: "秦朝", value: "秦朝"},
  {label: "东周（春秋、战国）", value: "东周（春秋、战国）"},
  {label: "西周", value: "西周"},
  {label: "商朝", value: "商朝"},
  {label: "夏朝", value: "夏朝"}
]);

// 富文本编辑器创建完成的回调
const handleCreated = (editor) => {
  editorRef.value = editor // 记录编辑器实例
}

// 关闭对话框时的处理函数
const close = () => {
  formRef0.value.resetFields()
  formRef1.value.resetFields()
  formRef2.value.resetFields()
  formRef3.value.resetFields()
  stepsIndex.value = 0
  selectedOptions.value = []
  emits('update:modelValue', false)
}

// 组件卸载前清理编辑器实例
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

// 添加历史人物方法
const addFigure = () => {
  form.value.related_figures.push({
    name: '',
    description: ''
  });
}

// 移除历史人物方法
const removeFigure = (index) => {
  form.value.related_figures.splice(index, 1);
}

// 添加历史事件方法
const addEvent = () => {
  form.value.related_events.push({
    name: '',
    date: '',
    description: ''
  });
}

// 移除历史事件方法
const removeEvent = (index) => {
  form.value.related_events.splice(index, 1);
}
</script>

// 组件样式定义
<style scoped lang="scss">
.avatar-uploader {
  width: 200px;
  height: 200px;
  border: 1px dashed #d9d9d9;
  border-radius: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;

  .avatar-delete {
    color: red;
    font-size: 22px;
    z-index: 999;
    position: absolute;
    top: 10px;
    right: 10px;
  }
}

.dialog {
  height: 700px;
  overflow-y: auto;
}
</style>
